<template>
  <WidgetBase class="fa-widget-text" :data="data" @drop.native.stop>
    <span
      v-if="data.isDone"
      class="fa-widget-text__text"
      :class="isTextarea ? 'is-textarea' : 'is-text'"
      :style="style"
      :title="data.value"
      >{{ data.value }}</span
    >

    <template v-else>
      <WidgetSourceIcon v-if="(data.isSet || data.isView) && data.sourceItem && data.sourceItem.icon" :data="data" />

      <Component
        v-if="data.option.componentExtend"
        :is="data.option.componentExtend"
        :data="data"
        :editable="editable"
        v-bind="attrs"
        :style="style"
        :listens="listens"
        :title="data.isView ? data.value : ''"
      />
    </template>
  </WidgetBase>
</template>

<script lang="ts">
import { computed, defineComponent, inject, nextTick, ref, watch } from 'vue'
import { Viewer, WidgetType } from '@/types'
import { Widget } from '@/models'
import { getTextPlaceholder } from '../input/utils'
import { GLOBAL_KEYBOARD } from '@/components/contract/hotkey/useHotkey'
import WidgetBase from '@/components/widget-base/WidgetBase.vue'
import WidgetSourceIcon from '@/components/widget-source/WidgetSourceIcon.vue'

/** 文本框控件 */
export default defineComponent({
  name: 'FaWidgetText',

  components: { WidgetBase, WidgetSourceIcon },

  props: {
    /** 控件数据 */
    data: {
      type: Widget,
      required: true
    }
  },

  setup(props) {
    const viewer = inject('Viewer') as Viewer

    /** 是否多行文本 */
    const isTextarea = computed(() => props.data.type === WidgetType.TEXTAREA)

    /** 是否允许编辑 */
    const editable = ref(false)

    // 默认使用模式、未指定数据来源才允许编辑。
    // 设置模式双击后开启编辑
    watch(
      () => props.data.mode + props.data.source,
      () => {
        const widget = props.data
        editable.value = widget.isUse && !widget.sourceItem
      },
      {
        immediate: true
      }
    )

    return {
      /** 是否允许编辑 */
      editable,

      /** 是否多行文本 */
      isTextarea,

      /** 样式 */
      style: computed(() => {
        const widget = props.data
        const { text } = widget

        return {
          fontSize: widget.fontSizeValue,
          fontFamily: widget.fontFamilyValue as string,
          textAlign: text.textAlign,
          height: `${widget.h}px`,
          // 已完成模式单行文本使用控件高度作为行高展示文本
          lineHeight: (widget.isDone && widget.type !== WidgetType.TEXTAREA && `${widget.h}px`) || undefined
        }
      }),

      /** 文本框属性 */
      attrs: computed(() => {
        const widget = props.data
        const { text } = widget
        const readonly = !editable.value

        return {
          class: ['fa-widget-text__input', { 'is-editable': !readonly }],

          placeholder: getTextPlaceholder(widget),

          /** 只读 */
          readonly,

          // IE11 禁止只读聚焦
          unselectable: (!readonly ? 'on' : undefined) as undefined,

          /** 最大长度 */
          maxlength: text.maxLength || undefined
        }
      }),

      /** 监听事件 */
      listens: {
        /** 编辑时阻止拖拽 */
        mousedown(e: MouseEvent) {
          if (editable.value) e.stopPropagation()
        },

        /** 设置模式下双击可编辑 */
        async dblclick(e: MouseEvent) {
          const widget = props.data
          const ipt = e.target as HTMLInputElement

          if (widget.isSet && !editable.value && !widget.sourceItem) {
            const val = ipt?.value || ''

            editable.value = true

            await nextTick()

            if (ipt) {
              ipt.value = ''
              ipt.focus()
              ipt.value = val
            }
          }
        },

        /** 聚焦 */
        focus() {
          // Ctrl/Cmd 点击不聚焦
          if (GLOBAL_KEYBOARD.ctrlKey || GLOBAL_KEYBOARD.metaKey) return

          viewer.activeWidgetId = props.data.id
        },

        /** 失焦更新值 */
        blur() {
          const widget = props.data

          widget.value = (widget.value || '').trim()

          if (widget.isSet) editable.value = false
        }
      }
    }
  }
})
</script>

<style lang="scss">
.fa-widget-text__input,
.fa-widget-text__text {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  color: $color-text-primary;
  line-height: 1;
  letter-spacing: 0;
  vertical-align: top;
}

.fa-widget-text__text {
  display: block;

  // 单行文本超出截取
  &.is-text {
    overflow: hidden;
    white-space: pre;
    text-overflow: ellipsis;
  }

  // 多行文本强制换行
  &.is-textarea {
    overflow: auto;
    white-space: pre-wrap;
    word-break: break-all;
  }
}

.fa-widget-text .fa-widget-source-icon {
  position: absolute;
  top: 50%;
  left: 2px;
  width: 1em;
  margin-top: -0.5em;
}

.fa-widget-text__input {
  padding: 0;
  background-color: transparent;
  border: none;
  transition: all ease-in-out 0.25s;
  resize: none;

  .fa-widget-source-icon + & {
    padding-left: 20px;
  }

  &:focus {
    outline: none;
  }

  &::placeholder {
    color: $color-text-placeholder;
  }

  .widget-mode-set & {
    cursor: move;
  }

  &.is-editable {
    cursor: text;
  }
}
</style>
